package cn.shop.front.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.shop.base.MyServiceImpl;
import cn.shop.front.mapper.FrontUserMapper;
import cn.shop.front.service.FrontUserService;
import cn.shop.thiredparty.entity.AuthResult;
import cn.shop.thiredparty.entity.IdAuthCode;
import cn.shop.thiredparty.service.ThiredpartyService;
import cn.shop.transcation.frontUserModule.FrontUser;
import cn.shop.utils.ApiResult;
import cn.shop.utils.constant.Constant;
import cn.shop.utils.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 购物平台用户表(FrontUser)表服务实现类
 *
 * @author jzw
 * @since 2022-01-07 15:45:20
 */
@Service("frontUserService")
public class FrontUserServiceImpl extends MyServiceImpl<FrontUserMapper, FrontUser> implements FrontUserService {

	@Resource
	private ThiredpartyService thiredpartyService;

	@Override
	public FrontUser wxuserCreate(String headimgurl, String unionid) {
		String username = "wx" + RandomUtil.randomString(6);
		String password = RandomUtil.randomNumbers(8);
		FrontUser wxuser = new FrontUser();
		wxuser.setAccount(username);
		wxuser.setPassword(password);
		wxuser.setAvatar(headimgurl);
		wxuser.setUnionId(unionid);
		wxuser.setCanRename(true);
		boolean success = insert(wxuser);
		if (success) {
			return wxuser;
		}
		throw new ServiceException("网站账户注册失败，请重试");
	}

	/**
	 * 新增数据
	 *
	 * @param frontUser 实体对象
	 * @return 新增结果
	 * @author jzw
	 * @since 2022-01-07 15:45:19
	 */
	@Override
	public boolean insert(FrontUser frontUser) {
		LambdaQueryWrapper<FrontUser> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(FrontUser::getAccount, frontUser.getAccount());
		FrontUser user = baseMapper.selectOne(wrapper);
		Assert.isNull(user, "当前账户已存在");
		String password = frontUser.getPassword();
		frontUser.setPassword(DigestUtil.bcrypt(password));
		return SqlHelper.retBool(baseMapper.insert(frontUser));
	}

	/**
	 * 获取验证码
	 *
	 * @author jzw
	 * @since 2021/11/4 14:03
	 */
	@Override
	public Dict verificationCode(String token) {
		if (StrUtil.isBlank(token)) {
			token = IdUtil.fastUUID();
		}
		//定义图形验证码的长、宽、验证码字符数、干扰元素个数
		LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 32, 4, 4);
		String imageBase64 = captcha.getImageBase64Data();
		SaSession saSession = SaSessionCustomUtil.getSessionById(token);
		saSession.delete(Constant.CAPTCHA_SESSION_KEY);
		saSession.set(Constant.CAPTCHA_SESSION_KEY, captcha.getCode());
		saSession.updateTimeout(300);
		return Dict.create().set("captchaToken", token).set("captcha", imageBase64).set("code", captcha.getCode());
	}

	@Override
	public ApiResult<Map<String, Object>> realNameAuthentication(long id, String name, String identityCard) {
		name = StrUtil.trim(name);
		identityCard = StrUtil.trim(identityCard);
		AuthResult result = thiredpartyService.idCardAuth(identityCard, name);
		if (!IdAuthCode.C10000.code().equals(result.getCode())) {
			return ApiResult.fail("实名认证失败");
		}
		if (!AuthResult.State.SAME.code().equals(result.getData().getResult())) {
			return ApiResult.fail("请检查身份证与姓名是否一致");
		}
		int age = IdcardUtil.getAgeByIdCard(identityCard);
		if (age < 18) {
			return ApiResult.fail("未成年人无法通过实名认证！");
		}
		FrontUser update = new FrontUser();
		update.setName(name);
		update.setIdentityCard(identityCard);
		update.setCertification(true);
		return ApiResult.result(update(update, Wrappers.<FrontUser>lambdaQuery().eq(FrontUser::getId, id)));
	}

	@Override
	public boolean setTransactionPassword(long id, String password) {
		FrontUser update = new FrontUser();
		update.setTransactionPassword(DigestUtil.bcrypt(password));
		return update(update, Wrappers.<FrontUser>lambdaQuery().eq(FrontUser::getId, id));
	}

	@Override
	public boolean updateLoginPassword(long id, String password) {
		FrontUser update = new FrontUser();
		update.setPassword(DigestUtil.bcrypt(password));
		return update(update, Wrappers.<FrontUser>lambdaQuery().eq(FrontUser::getId, id));
	}

	@Override
	public boolean updateAccount(long id, String account) {
		FrontUser update = new FrontUser();
		update.setAccount(account);
		update.setCanRename(false);
		return update(update, Wrappers.<FrontUser>lambdaQuery().eq(FrontUser::getId, id));
	}

	@Override
	public boolean setAutoWithdraw(long id, Boolean autoWithdraw) {
		FrontUser update = new FrontUser();
		update.setAutoWithdraw(autoWithdraw);
		return update(update, Wrappers.<FrontUser>lambdaQuery().eq(FrontUser::getId, id));
	}
}

